<template>
  <div class="user-info-container" style=" min-height: 100vh; padding: 20px;">
    <!-- 个人信息展示 -->
    <el-card class="user-info-card">
      <div class="user-info-header">
        <el-avatar :size="80" :src="userInfo.userImg" style="margin-left: 100px;"/>
        <div class="user-info-details">
          <h2>{{ userInfo.userName }}</h2>
          <p>{{ userInfo.userPhone }}</p>
          <!-- 添加身份标签 -->
          <el-tag v-for="role in userInfo.userRoles" :key="roleId" type="success" class="user-tag">{{
              role.roleName
            }}
          </el-tag>
        </div>
        <!-- 账户余额和积分展示 -->
        <div class="user-balance-container">
          <div class="user-balance">余额：￥{{ userInfo.userMoney }}</div>
          <div class="user-integral">积分：{{ userInfo.userPoint }}</div>
        </div>
        <!-- 添加修改信息按钮 -->
        <div>
          <el-button type="primary" @click="rechargeDialogVisible = true">充值</el-button>
          <el-button type="primary" @click="showModifyForm = !showModifyForm">修改个人信息</el-button>
        </div>

      </div>
    </el-card>
    <!-- 用户信息修改表单 -->
    <el-card class="user-info-modify-card" v-if="showModifyForm">
      <h3>修改个人信息</h3>
      <el-form :model="modifyForm" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户名">
              <el-input v-model="modifyForm.userName"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input type="password" v-model="modifyForm.userPassword"></el-input>
            </el-form-item>
            <el-form-item label="确认密码">
              <el-input type="password" v-model="modifyForm.confirmPassword"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="头像">
              <el-upload
                  class="avatar-uploader"
                  :action="modifyForm.uploadImgServer"
                  accept="jpg,jpeg,png"
                  :headers="{ 'hw-token': modifyForm.token }"
                  :show-file-list="false"
                  :before-upload="handleBeforeUpload"
                  :on-success="handleUrlSuccess"
              >
                <img style="width: 100px; height: 100px; border: 1px solid #8c939d;" v-if="modifyForm.userImg"
                     :src="modifyForm.userImg" class="avatar">
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="submitModifyForm">提交修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 订单管理 -->
    <el-card class="orders-management-card">
      <h3>订单管理</h3>
      <el-table :data="orderState.orderItems" style="width: 100%">
        <el-table-column prop="orderId" label="订单号" width="180"/>
        <!-- <el-table-column prop="addressId" label="地址" width="180" /> -->
        <el-table-column label="结算方式">
          <template #default="scope">
            <span>{{ scope.row.giveType === '0' ? '积分' : '现金' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalMoney" label="金额"/>
        <el-table-column prop="totalPoint" label="积分"/>
        <el-table-column label="状态">
          <template #default="scope">
            <span v-if="scope.row.status === 0">进行中</span>
            <span v-else-if="scope.row.status === 1">完成</span>
            <span v-else-if="scope.row.status === 2">取消</span>
            <span v-else-if="scope.row.status === 3">异常</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleOrderDetail(scope.row)">详情</el-button>
            <!--            <el-button type="text" @click="handleDeleteOrder(scope.row)">删除</el-button>-->
            <el-button v-if="scope.row.status === 0" type="text" @click="handleCancelOrder(scope.row)">取消订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="orderState.currentPage"
          :page-size="orderState.pageSize"
          :total="orderState.total"
          layout="prev, pager, next"
          @current-change="handleOrderPageChange"
      />
    </el-card>
    <!-- 用户地址管理 -->
    <el-card class="address-management-card">
      <div class="address-management-header">
        <h3>地址管理</h3>
        <el-button type="primary" @click="handleAddAddress">添加新地址</el-button>
      </div>
      <el-table :data="addressState.addressItems" style="width: 100%">
        <el-table-column prop="name" label="收货人" width="180"/>
        <el-table-column prop="phoneNumber" label="电话" width="180"/>
        <el-table-column prop="address" label="地址"/>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleEditAddress(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleDeleteAddress(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="addressState.currentPage"
          :page-size="addressState.pageSize"
          :total="addressState.total"
          layout="prev, pager, next"
          @current-change="handleAddressPageChange"
      />

      <!-- 添加地址表单 -->
      <el-dialog v-model="addAddressDialogVisible" title="添加新地址" width="30%">
        <el-form :model="addAddressForm" label-width="80px">
          <el-form-item label="收货人">
            <el-input v-model="addAddressForm.name"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="addAddressForm.phoneNumber"></el-input>
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="addAddressForm.address"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addAddressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddAddress">确定</el-button>
        </template>
      </el-dialog>

      <!-- 编辑地址表单 -->
      <el-dialog v-model="editAddressDialogVisible" title="编辑地址" width="30%">
        <el-form :model="editAddressForm" label-width="80px">
          <el-form-item label="收货人">
            <el-input v-model="editAddressForm.name"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="editAddressForm.phoneNumber"></el-input>
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="editAddressForm.address"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editAddressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditAddress">确定</el-button>
        </template>
      </el-dialog>
    </el-card>

    <!-- 充值弹窗   -->
    <el-dialog v-model="rechargeDialogVisible" title="充值" width="30%">
      <el-form :model="rechargeForm" label-width="80px" :rules="rechargeRules">
        <el-form-item label="充值金额">
          <el-input-number v-model="rechargeForm.count"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">
            充值
          </el-button>
          <el-button @click="closeRechargeForm()">取消</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="orderDetailDialogVisible" title="订单详情" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ orderDetail.orderId }}</el-descriptions-item>
        <el-descriptions-item label="用户">{{ orderDetail.sysUser.userName }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ orderDetail.address.address }}</el-descriptions-item>
        <el-descriptions-item label="结算方式">{{
            orderDetail.giveType === 0 ? '积分' : '现金'
          }}
        </el-descriptions-item>
        <el-descriptions-item label="金额">{{ orderDetail.totalMoney }}</el-descriptions-item>
        <el-descriptions-item label="积分">{{ orderDetail.totalPoint }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <span v-if="orderDetail.status === 0">进行中</span>
          <span v-else-if="orderDetail.status === 1">完成</span>
          <span v-else-if="orderDetail.status === 2">取消</span>
          <span v-else-if="orderDetail.status === 3">异常</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-row title="订单详情" border>

        <el-table border :data="orderDetails" style="width: 100%">
          <el-table-column prop="medicineCount" label="药品数量"/>
          <el-table-column prop="medicines.medicineName" label="药品名"/>
        </el-table>
      </el-row>
      <template #footer>
        <el-button type="primary" @click="orderDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, onMounted, ref} from 'vue';
import axios from 'axios';
import {ElMessage, ElMessageBox} from 'element-plus';
import {getAddressList, addUserAddress, updateUserAddress, deleteUserAddress} from '@/api/userAddress'
import {getOrderList, updateOrder, deleteOrder, getOrderDetail, overOrder, cancelOrder} from '@/api/order'
import {userUpdate, doLogout, updateUserInfo, recharge, profile} from '@/api/user'
import {localGet, ossPath, localRemove, uploadImgServer} from '@/utils';
import md5 from 'js-md5';
import {useRouter} from 'vue-router'

const router = useRouter()

// import { useLoginStore } from '@/store/login.js'
// const store = useLoginStore()
const userInfo = ref({})
const addAddressDialogVisible = ref(false)
const editAddressDialogVisible = ref(false) // 新增编辑地址对话框的显示状态
const editAddressForm = reactive({ // 新增编辑地址表单
  addressId: '',
  userId: '',
  name: '',
  phoneNumber: '',
  address: ''
})
const addAddressForm = reactive({
  name: '',
  phoneNumber: '',
  address: ''
})
const addressState = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0, // 总条数
  pages: 1,
  addressItems: []
});
const orderState = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0, // 总条数
  pages: 1,
  orderItems: []
});


const handleEditAddress = (address) => {
  console.log('编辑地址', address);
  // 填充编辑表单数据
  editAddressForm.addressId = address.addressId;
  editAddressForm.name = address.name;
  editAddressForm.userId = address.userId;
  editAddressForm.phoneNumber = address.phoneNumber;
  editAddressForm.address = address.address;
  editAddressDialogVisible.value = true; // 显示编辑地址对话框
};

const submitEditAddress = () => {
  updateUserAddress(editAddressForm.addressId, editAddressForm).then(response => {
    ElMessage.success('修改地址成功');
    editAddressDialogVisible.value = false;
    // 刷新地址列表
    getAddressList({
      current: addressState.currentPage,
      size: addressState.pageSize
    }).then(response => {
      addressState.addressItems = response.data.data.records;
      addressState.total = response.data.data.total;
      addressState.currentPage = response.data.data.current;
      addressState.pages = response.data.data.pages;
    }).catch(error => {
      console.error('获取地址数据失败:', error);
      ElMessage.error('获取地址数据失败');
    });
  }).catch(error => {
    console.error('修改地址失败:', error);
    ElMessage.error('修改地址失败');
  });
};

const handleDeleteAddress = (address) => {
  ElMessageBox.confirm('确定删除该地址吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUserAddress(address.addressId).then(response => {
      ElMessage.success('删除地址成功');
      addressState.addressItems = addressState.addressItems.filter(addr => addr.id !== address.id);
    }).catch(error => {
      console.error('删除地址失败:', error);
      ElMessage.error('删除地址失败');
    });
  }).catch(() => {
    // 用户取消删除
  });
};

const handleAddAddress = () => {
  addAddressDialogVisible.value = true
};

const submitAddAddress = () => {
  addUserAddress(addAddressForm).then(response => {
    ElMessage.success('添加地址成功');
    addAddressDialogVisible.value = false
    // 刷新地址列表
    getAddressList({
      current: addressState.currentPage,
      size: addressState.pageSize
    }).then(response => {
      addressState.addressItems = response.data.data.records;
      addressState.total = response.data.data.total;
      addressState.currentPage = response.data.data.current;
      addressState.pages = response.data.data.pages;
    }).catch(error => {
      console.error('获取地址数据失败:', error);
      ElMessage.error('获取地址数据失败');
    });
  }).catch(error => {
    console.error('添加地址失败:', error);
    ElMessage.error('添加地址失败');
  });
};

const handleAddressPageChange = (page) => {
  addressState.currentPage = page;
  getAddressList({
    current: addressState.currentPage,
    size: addressState.pageSize
  }).then(response => {
    addressState.addressItems = response.data.data.records;
    addressState.total = response.data.data.total
    addressState.currentPage = response.data.data.current
    addressState.pages = response.data.data.pages
  }).catch(error => {
    console.error('获取地址数据失败:', error);
    ElMessage.error('获取地址数据失败');
  });
};

const handleOrderPageChange = (page) => {
  orderState.currentPage = page;
  // 获取订单数据
};
const orderDetail = ref({})
const orderDetailDialogVisible = ref(false)


const orderDetails = ref([]);
const handleOrderDetail = async (order) => {
  Object.assign(orderDetail.value, order)
  await getOrderDetail(order.orderId).then((res) => {
    // orderDetail.value = res.data.data;
    Object.assign(orderDetail.value, res.data.data)
    orderDetails.value = res.data.data.orderDetailDtos
    console.log("最终的详情：", orderDetail.value)
    console.log("最终的详情：", orderDetails.value)
    orderDetailDialogVisible.value = true;
  }).catch(error => {
    console.log('获取订单详情失败', error);
  });
};

const handleDeleteOrder = (order) => {
  ElMessageBox.confirm('确定删除该订单吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOrder(order.orderId).then(response => {
      ElMessage.success('删除订单成功');
      orderState.orderItems = orderState.orderItems.filter(item => item.orderId !== order.orderId);
    }).catch(error => {
      console.error('删除订单失败:', error);
      ElMessage.error('删除订单失败');
    });
  }).catch(() => {
    // 用户取消删除
  });
};

const handleCancelOrder = (order) => {
  ElMessageBox.confirm('确定取消该订单吗？', '取消确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cancelOrder(order.orderId).then(response => {
      ElMessage.success('取消订单成功');
      order.status = 2; // 更新订单状态为取消
    }).catch(error => {
      console.error('取消订单失败:', error);
      ElMessage.error('取消订单失败');
    });
  }).catch(() => {
    // 用户取消操作
  });
};

const modifyForm = reactive({
  userName: '',
  userPassword: '',
  confirmPassword: '',
  userImg: '',
  uploadImgServer: uploadImgServer, // 图片上传服务器地址
  token: localGet('token') || '' // 上传图片所需的token
});

const handleAvatarSuccess = (response, file) => {
  modifyForm.userImg = URL.createObjectURL(file.raw);
};

// 上传图片前的验证
const handleBeforeUpload = (file) => {
  const sufix = file.name.split('.')[1] || '';
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片');
    return false;
  }
};

// 上传图片成功后的处理
const handleUrlSuccess = (val) => {
  modifyForm.userImg = ossPath + val.data || ''; // 修改为 medicineImg
};
const submitModifyForm = () => {
  if (modifyForm.userPassword !== modifyForm.confirmPassword) {
    ElMessage.error('两次输入的密码不一致');
    return;
  }

  if (modifyForm.userPassword == '') {
    modifyForm.userPassword = userInfo.value.userPassword
  } else {
    modifyForm.userPassword = md5(modifyForm.userPassword)
  }
  // 调用API提交修改
  // 这里假设有一个 updateUserInfo API
  updateUserInfo(modifyForm).then(async (response) => {
    // 判断新密码与原密码是否一致
    ElMessage.success('修改成功');
    // 更新用户信
    ElMessage.success('修改成功');
    showModifyForm.value = false;
    // 退出登录
    await doLogout({'token': localGet('token')}).then(() => {
      // 退出之后，将本地保存的 token  清理掉
      localRemove('token')
      localRemove('type')
      localRemove('userInfo')
      // 回到登录页
      router.push({path: '/login'})
    })
  }).catch(error => {
    ElMessage.error('修改失败');
  });
};

const showModifyForm = ref(false);

// 充值弹窗
const rechargeDialogVisible = ref(false);
// 构建充值数据
const rechargeForm = reactive({
  count: ''
});
const rechargeRules = {
  count: [
    {required: true, message: '请输入充值金额', trigger: 'blur'},
    {type: 'number', message: '充值金额必须为数字值'}
  ]
};
// 确认充值
const submitForm = async () => {
  await recharge({
    count: rechargeForm.count
  }).then(response => {
    ElMessage.success('充值成功');
    profile({token: localGet('token')}).then((res) => {
      const user = res.data.data
      console.log('userInfo', user);
      // store.profile(userInfo)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      // 刷新页面
      userInfo.value.userMoney = user.userMoney
    }).catch(e => {
      console.log('获取用户信息失败', e);
    })
    rechargeForm.count = '';
    rechargeDialogVisible.value = false;
  }).catch(error => {
    console.error('充值失败:', error);
  })

};
const closeRechargeForm = () => {
  rechargeForm.count = '';
  rechargeDialogVisible.value = false;
};
onMounted(() => {
  // userInfo.value = store.loginUserInfo
  console.log("当前用户", JSON.parse(localStorage.getItem('userInfo')))

  userInfo.value = JSON.parse(localStorage.getItem('userInfo'))
  // 获取地址数据
  getAddressList({
    current: addressState.currentPage,
    size: addressState.pageSize
  }).then(response => {
    addressState.addressItems = response.data.data.records;
    addressState.total = response.data.data.total
    addressState.currentPage = response.data.data.current
    addressState.pages = response.data.data.pages
  }).catch(error => {
    console.error('获取地址数据失败:', error);
    ElMessage.error('获取地址数据失败');
  });
  // 获取订单数据
  getOrderList({
    current: orderState.currentPage,
    size: orderState.pageSize
  }).then(response => {
    orderState.orderItems = response.data.data.records;
    orderState.total = response.data.data.total
    orderState.currentPage = response.data.data.current
    orderState.pages = response.data.data.pages
  }).catch(error => {
    console.error('获取订单数据失败:', error);
    ElMessage.error('获取订单数据失败');
  });
})

</script>

<style scoped>
.user-info-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.user-info-card {
  margin-bottom: 20px;
}

.user-info-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-info-details {
  margin-left: 20px;
}

.orders-management-card {
  margin-bottom: 20px;
}

.address-management-card {
  margin-bottom: 20px;
}

.address-management-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-info-modify-card {
  margin-bottom: 20px;
}

.avatar-uploader .el-upload {
  border: 2px dashed #222832;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #222832;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>